<?php
/**
 * Created by PhpStorm.
 * User: fengdh
 * Date: 2019/9/4
 * Time: 9:56
 */

namespace console\controllers\platform;

use business\elasticsearch\models\ProcurementModel;
use business\procurement\services\ProcurementService;
use common\cache\CacheManager;
use common\utils\DateTimeUtils;
use console\controllers\BaseIndexController;

class ProcurementIndexController extends BaseIndexController
{
    public function actionFull()
    {
        $procurement_service = new ProcurementService();
        $recruit_ids = $procurement_service->getRecruitIdsList();
        if (!empty($recruit_ids)) {
            $this->handProcurementData($recruit_ids, 'recruit');
        }
        $bidding_ids = $procurement_service->getBiddingIdsList();
        if (!empty($bidding_ids)) {
            $this->handProcurementData($bidding_ids, 'bidding');
        }
        echo 'all procurement had handle!';
        return true;
    }

    public function actionIncrement()
    {
        //1.获取上次查询的时间点
        $timestamp = CacheManager::get(BaseIndexController::LATEST_PLATFORM_PROCUREMENT_QUERY_TIME_KEY);
        $now = DateTimeUtils::time();
        if (empty($timestamp)) {
            $timestamp = strtotime('-' . BaseIndexController::DEFAULT_INCREMENT_TIME . ' minutes', $now);
        }
        $last_query_time = date('Y-m-d H:i:s', $timestamp);
        \Yii::info("elasticsearch increment time of platform procurement index update is " . $last_query_time);
        $procurement_service = new ProcurementService();
        $recruit_ids = $procurement_service->getRecruitIdsList($last_query_time);
        $bidding_ids = $procurement_service->getBiddingIdsList($last_query_time);
        CacheManager::set(BaseIndexController::LATEST_PLATFORM_PROCUREMENT_QUERY_TIME_KEY, $now, 0);
        if (empty($recruit_ids) && empty($bidding_ids)) {
            echo '没有找到商机';
            return;
        }
        if (!empty($recruit_ids)) {
            $this->handProcurementData($recruit_ids, 'recruit');
        }
        if (!empty($bidding_ids)) {
            $this->handProcurementData($bidding_ids, 'bidding');
        }
    }

    private function handProcurementData($procurement_ids, $type = 'recruit')
    {
        $procurement_count = count($procurement_ids);
        $loop_count = intval($procurement_count / $this->_every_time_number) + 1;
        echo '总数: ' . $loop_count . PHP_EOL;
        echo '正在进行: ';
        for ($i = 0; $i < $loop_count; $i++) {
            echo $i . ' ';
            for ($j = $i * $this->_every_time_number; $j < ($i + 1) * $this->_every_time_number && $j < $procurement_count; $j++) {
                $procurement_id = $procurement_ids[$j];
                $procurement_info = [];
                try {
                    $procurement_info = $this->getProcurementInfo($procurement_id, $type);
                    if (isset($procurement_info['sjId'])) {
                        $procurement_es_model = ProcurementModel::findOne($procurement_info['sjId']);
                        //校验条件
                        $checkResult = $this->checkConstructIndexCondition($procurement_info['sjId'], $procurement_info);
                        if (!$checkResult['success']) {
                            if ($procurement_es_model) {
                                $procurement_es_model->deleteAll(['_id'=>$procurement_info['sjId']]);
                            }
                            continue;
                        }
                        if (empty($procurement_es_model)) {
                            $procurement_es_model = new ProcurementModel();
                            $procurement_es_model->primaryKey = $procurement_info['sjId'];
                        }
                        $procurement_es_model->setAttributes($procurement_info, false);
                        $procurement_es_model->indexCreatedTime = date('Y-m-d H:i:s');
                        $rs = $procurement_es_model->save();
                        if (!$rs) {
                            \Yii::error('update es_procurement failed! procurement_id:' . $procurement_info['sjId']);
                        }
                    }
                } catch (\Exception $e) {
                    echo 'update failed! type is ' . $type . ', procurement_id:' . $procurement_info['sjId'] . PHP_EOL;
                    $title = isset($procurement_info['sjTitle']) ? $procurement_info['sjTitle'] : '';
                    $this->saveUnIndexData('es_procurement', $title, $procurement_info['sjId'], $e);
                }
            }
        }
    }

    /**
     * @param $procurement_id
     * @param string $type
     * @return array
     * @throws \yii\db\Exception
     */
    private function getProcurementInfo($procurement_id, $type = 'recruit')
    {
        $procurement_service = new ProcurementService();
        if ($type == 'recruit') {
            $basicInfo = $procurement_service->getRecruitBasicInfo($procurement_id);
        } else {
            $basicInfo = $procurement_service->getBiddingBasicInfo($procurement_id);
            $bindDetail = $procurement_service->getBidDetail($procurement_id);
            $detail = empty($bindDetail["detail"]) ? "" : self::escapeString($bindDetail["detail"]);
            $basicInfo["shortDetail"] = mb_substr($detail,0,50,'utf-8');
        }
        $developerInfo = $procurement_service->getProcurementDeveloperInfo($basicInfo["sjDeveloperId"]);
        $czSassInfo = $procurement_service->getCzSassDeveloperInfo($basicInfo["sjDeveloperId"]);
        return array_merge($basicInfo, $developerInfo,$czSassInfo);
    }

    /**
     * 转义字符串
     * @param $escapeString
     * @return string|string[]
     */
    private function escapeString($escapeString){
        $escapeString = htmlspecialchars_decode($escapeString);
        $escapeString = str_replace("&nbsp;","",$escapeString);
        $escapeString = str_replace("\n", "<br/>", $escapeString);
        $escapeString = str_replace("\r\n", "<br/>", $escapeString);
        $escapeString = str_replace("\r", "<br/>", $escapeString);
        return strip_tags($escapeString);
    }

    /**
     * 检查索引构建的条件
     * @param $procurementId
     * @param $procurementInfo
     * @return array
     */
    private function checkConstructIndexCondition($procurementId, $procurementInfo)
    {
        $result = [
            'success' => true,
            'errMsg' => ''
        ];

        //商机id为空
        if ($result['success'] && empty($procurementId)) {
            $result['errMsg'] = '商机Id为空，此条数据不会导入搜索引擎！';
            $result['success'] = false;
        }
        //商机name为测试数据
        if ($result['success'] &&
            ((!isset($procurementInfo['sjTitle']) || !strncmp($procurementInfo['sjTitle'], 'test_', 5)) ||
                (isset($procurementInfo['sjShortTitle']) && !strncmp($procurementInfo['sjShortTitle'], 'test_', 5)))
        ) {
            $result['errMsg'] = "此商机($procurementId)为测试数据，数据不会导入搜索引擎！";
            $result['success'] = false;
        }
        //商机发布的开发商为测试数据
        if ($result['success'] &&
            ((!isset($procurementInfo['sjDeveloperName']) || !strncmp($procurementInfo['sjDeveloperName'], 'test_',
                        5)) ||
                (isset($procurementInfo['sjDeveloperShortName']) && !strncmp($procurementInfo['sjDeveloperShortName'],
                        'test_', 5)))
        ) {
            $result['errMsg'] = "此商机($procurementId)所属开发商为测试数据，数据不会导入搜索引擎！";
            $result['success'] = false;
        }
        //商机状态不正常
        if ($result['success'] && !$procurementInfo['sjState']) {
            $result['errMsg'] = "此商机($procurementId)状态非正常，数据不会导入搜索引擎！";
            $result['success'] = false;
        }

        //条件校验失败操作
        if (!$result['success']) {
            $title = isset($procurementInfo['sjTitle']) ? $procurementInfo['sjTitle'] : '';
            $this->saveUnIndexData('es_procurement', $title, $procurementId, $result['errMsg']);
        }

        return $result;
    }

}